package study.sharding.shardingjdbc.support.sharding;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * 精确分片算法
 * （1）只支持 = in 的操作
 */
@Slf4j
public class CustomPreciseAlgorithm implements PreciseShardingAlgorithm<Long> {

    @Override
    public String doSharding(Collection<String> availableTargetNames,
                             PreciseShardingValue<Long> shardingValue) {
        //目标名称：db or table
        log.info(">>>>>> available_target_names= [{}]", StrUtil.join(",", availableTargetNames));
        //分片信息：分片表、分片列、分片值
        String logicTableName = shardingValue.getLogicTableName();
        String columnName = shardingValue.getColumnName();
        Long value = shardingValue.getValue();
        log.info(">>>>>> logic_table= [{}], column_name= [{}], value= [{}]", logicTableName, columnName, value);

        int size = availableTargetNames.size();
        for (String targetName : availableTargetNames) {
            //Step-1: 取模
            long mod = value % size;
            //Step-2: 匹配目标并返回
            if (StrUtil.endWith(targetName, NumberUtil.toStr(mod))) {
                log.info(">>>>>> [{}] Use Target [{}]", value, targetName);
                return targetName;
            }
        }
        throw new UnsupportedOperationException();
    }
}
